<?php
/**
 * Fake4
 * @copyright   Copyright(c) 2024-2034
 * @author      tianjie <527707665@qq.com>
 * @link        http://www.tinphp.com/
 */

namespace app\middleware;

use tian\MiddlewareInterface;
use tian\Response;
use tian\Request;

class AccessControlWare implements MiddlewareInterface
{
    public function handle(Request $request, $next): Response
    {
        //跨域请求中间件

        // 如果是options请求则返回一个空响应，否则继续向洋葱芯穿越，并得到一个响应
        //$response = $request->method() == 'OPTIONS' ? response() : $next($request);
        if ($request->method() == 'OPTIONS') {
            return response('');
        }

        // 给响应添加跨域相关的http头
//        $header = [
//            'Access-Control-Allow-Credentials' => 'true',
//            'Access-Control-Allow-Origin' => $request->header('origin', '*'),
//            'Access-Control-Allow-Methods' => $request->header('access-control-request-method', '*'),
//            'Access-Control-Allow-Headers' => $request->header('access-control-request-headers', '*'),
//        ];
//        $response->header($header);

        // 前置设置
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization');

        return $next($request);
    }

}